#!/usr/bin/poython3.6
# conding:utf-8
import zerorpc
from aiohttp import request, web_response, web, log

CONN_URL = "tcp://127.0.0.1:9000"

client = zerorpc.Client()
client.connect(CONN_URL)


async def targetshandler(request: web.Request):
    txt = client.get_agents()  # 通过zerorpc调用master端接口
    return web.json_response(txt)  # 返回json端数据


app = web.Application()

app.router.add_get('/task/targets', targetshandler)  # 使用get方法进行处理


async def taskhandler(request: web.Request):
    j = await  request.json()
    txt = client.add_task(j)
    return web.Response(text=txt, status=201)


app.router.add_post('/task', taskhandler)


async def taskresult(request: web.Request):
    j = await  request.json()
    txt = client.get_result(j)
    print(txt)
    if txt['code'] != 0:
        txt['output'] = '参数不正确，请重新输入'
    return web.json_response(txt)


app.router.add_post('/result', taskresult)

if __name__ == "__main__":
    web.run_app(app, host='0.0.0.0', port=80)
